import React, { Component } from 'react';
import { Card, Table, Button, message, Select, } from 'antd';
import { connect } from 'dva';
import PateoAuthButtons from '../../../components/common/PateoAuthButtons';
import moment from 'moment';
import styles from './index.less';
import router from 'umi/router';
import Ellipsis from '../../../components/Ellipsis';
import { filterAuth } from '@/support/common';
import { PlusOutlined } from '@ant-design/icons';
import PateoSearchForm from '../../../components/common/PateoSearchForm';

const mapStateToProps = (state: any) => ({
  appPicsConfig: state.appPicsConfig,
  loading: state.loading.models['appPicsConfig'],
  menu: state.menu,
});
interface StateClass {
  formValues?: any;
  pageParams?: {
    pageNo?: number;
    pageSize?: number;
  };
  seriesOptions?: Array<{ value: any; label: any }>;
  vehicleTypeOptions?: Array<{ value: any; label: any }>;
  [key: string]: any;
}
class AppPicsConfig extends Component<any, StateClass> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
      seriesOptions: [],
      vehicleTypeOptions: [],
      brandOptions: [],
      defaultBrand: '',
      selectBrand: '',
    };
  }
  componentDidMount() {
    const { dispatch } = this.props;
    //获取品牌数据
    dispatch({
     type: 'basedata/brandFetch',
     callback: (res:any) => {
       this.setState({ 
          brandOptions: res?.data,
         });
         if(this.props.location.state&&this.props.location.state.sourceRouter == 'appPics'){
           const brandData = JSON.parse(sessionStorage.getItem('appPicsBrandInfo')||'{}');
           const brandId = brandData&&brandData?.selectBrand
           this.setState({ 
             defaultBrand: brandId,
             selectBrand: brandId
            });
            this.getSeriesData(brandId);
            this.handleFreshPage(brandId);
         }else{
           this.setState({ 
             defaultBrand: res?.data[0].brandCode,
             selectBrand: res?.data[0].brandCode
            });
         this.getSeriesData(res?.data[0].brandCode);
         this.handleFreshPage(res?.data[0].brandCode);
         }
       }
   });
    // this.getSeriesData();
    // this.handleFreshPage();
  }
  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'appPicsConfig/initData',
    });
  }
  /**
   * 获取车系下拉数据
   */
  getSeriesData = (brandId:String) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'appPicsConfig/getFetchPage',
      payload: {
        url: '/msdevice/base/vehicle/series/bybrand/list',
        brandId 
      },
      callback: (resp: any) => {
        const data = resp.data;
        this.setState({
          seriesOptions: data.map((item: { seriesCode: any; seriesName: any }) => {
            return {
              value: item.seriesCode,
              label: item.seriesName,
            };
          }),
        });
      },
    });
  };

  /**
   * 获取车型组数据
   */
  getVehicleTypeData = (seriesCode: string) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'appPicsConfig/postData',
      payload: {
        url: '/vehicle/group/findBySeriesCode',
        seriesCode,
      },
      callback: (resp: any) => {
        const data = resp.data;
        this.setState({
          vehicleTypeOptions: data.map((item: any) => {
            return {
              value: item.sid,
              label: item.name,
            };
          }),
        });
      },
    });
  };
  handleFreshPage = (brandId:String) => {
    const { dispatch } = this.props;
    const { formValues, pageParams } = this.state;
    dispatch({
      type: 'appPicsConfig/fetchPageData',
      // type: 'appPicsConfig/queryList',
      payload: {
        url: '/vehicle/image/findList',
        brandId:brandId ,
        ...formValues,
        ...pageParams,
      },
    });
  };

  handleFormReset = () => {
    this.searchForm?.current.setFieldsValue({});
    this.setState({
      formValues: {},
      pageParams: {
        pageNo: 1,
        pageSize: 10,
      },
    });
  };
  // 分页时触发
  tableOnChange = (pagination: any) => {
    const {selectBrand } = this.state;
    const current = pagination.current;
    this.setState(
      {
        pageParams: {
          pageNo: current,
          pageSize: pagination.pageSize,
        },
      },
      () => {
        this.handleFreshPage(selectBrand);
      },
    );
  };

  /**
   * 删除
   * @param data
   */
  handleDelete = (sid: any) => {
    const { dispatch } = this.props;
    const {selectBrand } = this.state;
    dispatch({
      type: 'appPicsConfig/postData',
      payload: {
        url: `/vehicle/image/v2/delete/${sid}`,
      },
      callback: (response: any) => {
        if (response && response.statusCode == '0') {
          message.success('操作成功！');
          this.handleFreshPage(selectBrand);
        } else {
          message.error(response.statusMessage);
        }
      },
    });
  };

  /**
   * 详情 新增or编辑
   */
  handleDetail = (data?: any) => {
    const { formValues, pageParams, selectBrand } = this.state;
    const searchValues = {
      ...formValues,
      selectBrand
    };
    sessionStorage.setItem('appPicsBrandInfo', JSON.stringify(searchValues));
    if (data && data.sid) {
      sessionStorage.setItem('appPicsConfigData', JSON.stringify(data));
      router.push({
        pathname: '/remoteConfiguration/appPicsConfig/appPicsConfigEdit',
        state: { pageObj: pageParams, formValues, backUrl: '/remoteConfiguration/appPicsConfig',brandOption: this.state.brandOptions, brandId: this.state.selectBrand },
      });
    } else {
      sessionStorage.setItem('appPicsConfigData', '');
      router.push({
        pathname: '/remoteConfiguration/appPicsConfig/appPicsConfigAdd',
        state: { pageObj: pageParams, formValues, backUrl: '/remoteConfiguration/appPicsConfig',brandOption: this.state.brandOptions, brandId: this.state.selectBrand },
      });
    }
  };
  onBrandSelect = (value:any) =>{
    this.setState({
      selectBrand: value,
      formValues: {}
    }, ()=>{
      this.searchForm.current.resetFields();
      this.getSeriesData(value);
      this.handleFreshPage(value);
    })
  };
  render() {
    let {
      location: { pathname = '/' },
      loading,
      appPicsConfig: {
        pageList: { list = [], pagination },
      },
      menu: { permissions },
    } = this.props;

    const { formValues, seriesOptions, vehicleTypeOptions, pageParams,brandOptions,defaultBrand, selectBrand } = this.state;
    const options = brandOptions.map((item:any)=>{
      return {
        label: item.brandName,
        value: item.brandCode
      }
    })
    const columns: Array<any> = [
      {
        title: '车系',
        // dataIndex: 'vehicleSeriesId',
        dataIndex: 'vehicleSeriesName',
        // render: (text: any) => {
        //   return seriesOptions?.find(item => {
        //     return item.value == text;
        //   })?.label;
        // },
      },
      {
        title: '车型组',
        // dataIndex: 'vehicleTypeGroupId',
        dataIndex: 'vehicleTypeGroupName',
        // render: (text: any) => {
        //   return vehicleTypeOptions?.find(item => {
        //     return item.value == text;
        //   })?.label;
        // },
      },
      {
        title: '车身颜色',
        dataIndex: 'vehicleColorName',
        render: (text: any) => {
          return (
            <Ellipsis length={30} tooltip>
              {text === 'ALL' ? '不区分颜色' : text}
            </Ellipsis>
          );
        },
      },
      {
        title: '备注',
        dataIndex: 'remark',
        render: (text: any) => {
          return (
            <Ellipsis length={30} tooltip>
              {text}
            </Ellipsis>
          );
        },
      },
      {
        title: '操作人',
        dataIndex: 'createBy',
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        render: (text: any) => {
          return text && moment(text).format('YYYY-MM-DD HH:mm:ss');
        },
      },
      {
        title: '操作',
        dataIndex: '操作',
        key: 'opt',
        width: 150,
        render: (text: any, data: any) => {
          const btns = [
            {
              title: '编辑',
              key: 'edit',
              auth: 'appPicsConfig_edit',
              onConfirm: (e: any) => {
                e.stopPropagation();
                this.handleDetail(data);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'appPicsConfig_delete',
              message: '确定要删除当前APP图片配置吗？',
              Popconfirm: true,
              onConfirm: () => this.handleDelete(data.sid),
            },
          ];
          return <PateoAuthButtons btns={btns} max={1} pathname={pathname} />;
        },
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      showTotal: () => (
        <span>共&nbsp;{pagination === undefined ? 0 : pagination.total}&nbsp;条</span>
      ),
    };

    const searchItems = [
      {
        title: '车系',
        type: 'select',
        customStyle: 6,
        selectOptions: seriesOptions,
        onSelectChange: (seriesCode: any) => {
          this.searchForm?.current.setFieldsValue({ vehicleTypeGroup: null });
          seriesCode
            ? this.getVehicleTypeData(seriesCode)
            : this.setState({ vehicleTypeOptions: [] });
        },
        key: 'vehicleSeries',
      },
      {
        title: '车型组',
        type: 'select',
        customStyle: 6,
        selectOptions: vehicleTypeOptions,
        key: 'vehicleTypeGroup',
      },
    ];
    return (
      <div className={styles.container}>
        <div  style={{margin: '0px 10px 10px 10px'}}>
          <div style={{display:'inline-block'}}>
          <span>品牌：</span>
            </div>
            <div style={{display:'inline-block'}}>
                 <Select
                    allowClear={false}
                    placeholder="请选择品牌"
                    getPopupContainer={(triggerNode) => triggerNode.parentNode}
                    
                    onChange={this.onBrandSelect}
                    style={{width: '250px'}}
                    key={defaultBrand}
                    defaultValue={defaultBrand}
                    options={options}
                  >
                  </Select>
                  </div>
          </div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'appPicsConfig/fetchPageData',
              url: '/vehicle/image/findList',
              // extraArgs: {
              //   ...pageParams,
              //   brandId: selectBrand,
              // },
            }}
            extraArgs={{ brandId: selectBrand, ...pageParams,}}
            saveFormValues={(val: any) =>
              this.setState({
                formValues: Object.assign(formValues, val),
              })
            }
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card title="" bordered={false}>
          {filterAuth('appPicsConfig_add', permissions, pathname) ? (
            <div className="my_newItem">
              <Button
                size="small"
                icon={<PlusOutlined />}
                type="primary"
                onClick={() => this.handleDetail()}
              >
                新增
              </Button>
            </div>
          ) : null}
          <Table
            loading={loading}
            rowKey={row => row.sid}
            columns={columns}
            size="small"
            pagination={paginationProps}
            dataSource={list}
            onChange={this.tableOnChange}
          />
        </Card>
      </div>
    );
  }
}
export default connect(mapStateToProps)(AppPicsConfig);
